<template>
  <div class="drivers-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon><User /></el-icon>
            <span>司机管理</span>
          </div>
          <div class="header-actions">
            <el-button type="primary" @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
          </div>
        </div>
      </template>

      <!-- 筛选条件 -->
      <div class="filter-container">
        <el-form :inline="true" :model="filters" class="filter-form">
          <el-form-item label="司机状态">
            <el-select v-model="filters.status" placeholder="司机状态" clearable>
              <el-option label="全部" value="" />
              <el-option label="在线" value="online" />
              <el-option label="离线" value="offline" />
              <el-option label="服务中" value="busy" />
              <el-option label="暂停服务" value="suspended" />
            </el-select>
          </el-form-item>
          <el-form-item label="资质审核">
            <el-select v-model="filters.verified" placeholder="资质审核" clearable>
              <el-option label="全部" value="" />
              <el-option label="已审核" value="verified" />
              <el-option label="审核中" value="pending" />
              <el-option label="未通过" value="rejected" />
            </el-select>
          </el-form-item>
          <el-form-item label="关键词">
            <el-input v-model="filters.keyword" placeholder="司机姓名/手机/ID" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchDrivers">搜索</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 司机列表 -->
      <div class="drivers-list">
        <el-table
          :data="driversList"
          stripe
          border
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column prop="id" label="司机ID" width="100" />
          <el-table-column prop="name" label="姓名" width="100" />
          <el-table-column prop="phone" label="手机号" width="120" />
          <el-table-column prop="licenseType" label="驾照类型" width="100" align="center" />
          <el-table-column prop="carType" label="车辆类型" width="120" />
          <el-table-column prop="joinDate" label="加入日期" width="120" />
          <el-table-column label="资质状态" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.verified === 'verified'" type="success">已审核</el-tag>
              <el-tag v-else-if="scope.row.verified === 'pending'" type="warning">审核中</el-tag>
              <el-tag v-else-if="scope.row.verified === 'rejected'" type="danger">未通过</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="在线状态" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.status === 'online'" type="success">在线</el-tag>
              <el-tag v-else-if="scope.row.status === 'offline'" type="info">离线</el-tag>
              <el-tag v-else-if="scope.row.status === 'busy'" type="warning">服务中</el-tag>
              <el-tag v-else-if="scope.row.status === 'suspended'" type="danger">已暂停</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="rating" label="评分" width="100">
            <template #default="scope">
              <el-rate
                v-model="scope.row.rating"
                disabled
                text-color="#ff9900"
                score-template="{value}"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220" fixed="right">
            <template #default="scope">
              <el-button 
                size="small" 
                @click="showDriverDetail(scope.row)"
              >
                详情
              </el-button>
              <el-button 
                size="small"
                type="primary"
                @click="auditQualification(scope.row)"
                v-if="scope.row.verified === 'pending'"
              >
                审核资质
              </el-button>
              <el-button 
                size="small"
                type="danger"
                @click="toggleDriverStatus(scope.row)"
                v-if="scope.row.status !== 'suspended'"
              >
                暂停服务
              </el-button>
              <el-button 
                size="small"
                type="success"
                @click="toggleDriverStatus(scope.row)"
                v-else
              >
                恢复服务
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 司机详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="司机详情"
      width="800px"
    >
      <div class="driver-detail" v-if="currentDriver">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-descriptions title="个人信息" :column="2" border>
              <el-descriptions-item label="司机ID">{{ currentDriver.id }}</el-descriptions-item>
              <el-descriptions-item label="姓名">{{ currentDriver.name }}</el-descriptions-item>
              <el-descriptions-item label="手机号">{{ currentDriver.phone }}</el-descriptions-item>
              <el-descriptions-item label="邮箱">{{ currentDriver.email }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ currentDriver.gender }}</el-descriptions-item>
              <el-descriptions-item label="年龄">{{ currentDriver.age }}</el-descriptions-item>
              <el-descriptions-item label="加入日期">{{ currentDriver.joinDate }}</el-descriptions-item>
              <el-descriptions-item label="资质状态">
                <el-tag v-if="currentDriver.verified === 'verified'" type="success">已审核</el-tag>
                <el-tag v-else-if="currentDriver.verified === 'pending'" type="warning">审核中</el-tag>
                <el-tag v-else-if="currentDriver.verified === 'rejected'" type="danger">未通过</el-tag>
              </el-descriptions-item>
            </el-descriptions>
            
            <el-divider>驾驶信息</el-divider>
            
            <el-descriptions :column="2" border>
              <el-descriptions-item label="驾照类型">{{ currentDriver.licenseType }}</el-descriptions-item>
              <el-descriptions-item label="驾龄">{{ currentDriver.drivingYears }}年</el-descriptions-item>
              <el-descriptions-item label="车辆类型">{{ currentDriver.carType }}</el-descriptions-item>
              <el-descriptions-item label="车牌号">{{ currentDriver.carNumber }}</el-descriptions-item>
              <el-descriptions-item label="车辆颜色">{{ currentDriver.carColor }}</el-descriptions-item>
              <el-descriptions-item label="载客人数">{{ currentDriver.passengerCapacity }}人</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          
          <el-tab-pane label="统计数据" name="statistics">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-card shadow="hover" class="stat-card">
                  <div class="stat-header">总接单数</div>
                  <div class="stat-value">{{ currentDriver.stats.totalOrders }}</div>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card shadow="hover" class="stat-card">
                  <div class="stat-header">完成率</div>
                  <div class="stat-value">{{ currentDriver.stats.completionRate }}%</div>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card shadow="hover" class="stat-card">
                  <div class="stat-header">平均评分</div>
                  <div class="stat-value">
                    <el-rate
                      v-model="currentDriver.rating"
                      disabled
                      text-color="#ff9900"
                      score-template="{value}"
                    />
                  </div>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card shadow="hover" class="stat-card">
                  <div class="stat-header">累计收入</div>
                  <div class="stat-value">¥{{ currentDriver.stats.totalIncome.toFixed(2) }}</div>
                </el-card>
              </el-col>
            </el-row>
            
            <el-divider>近30天数据</el-divider>
            
            <div class="chart-container" ref="orderChartRef"></div>
          </el-tab-pane>
          
          <el-tab-pane label="资质证件" name="documents">
            <div class="documents-container">
              <el-row :gutter="20">
                <el-col :span="8">
                  <div class="document-card">
                    <div class="document-title">身份证正面</div>
                    <div class="document-image">
                      <el-image 
                        :src="currentDriver.documents.idCardFront" 
                        fit="contain"
                        :preview-src-list="[currentDriver.documents.idCardFront]"
                      />
                    </div>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="document-card">
                    <div class="document-title">身份证反面</div>
                    <div class="document-image">
                      <el-image 
                        :src="currentDriver.documents.idCardBack" 
                        fit="contain"
                        :preview-src-list="[currentDriver.documents.idCardBack]"
                      />
                    </div>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="document-card">
                    <div class="document-title">驾驶证</div>
                    <div class="document-image">
                      <el-image 
                        :src="currentDriver.documents.drivingLicense" 
                        fit="contain"
                        :preview-src-list="[currentDriver.documents.drivingLicense]"
                      />
                    </div>
                  </div>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="8">
                  <div class="document-card">
                    <div class="document-title">车辆行驶证</div>
                    <div class="document-image">
                      <el-image 
                        :src="currentDriver.documents.vehicleLicense" 
                        fit="contain"
                        :preview-src-list="[currentDriver.documents.vehicleLicense]"
                      />
                    </div>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="document-card">
                    <div class="document-title">车辆照片</div>
                    <div class="document-image">
                      <el-image 
                        :src="currentDriver.documents.vehiclePhoto" 
                        fit="contain"
                        :preview-src-list="[currentDriver.documents.vehiclePhoto]"
                      />
                    </div>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="document-card">
                    <div class="document-title">背景调查授权书</div>
                    <div class="document-image">
                      <el-image 
                        :src="currentDriver.documents.backgroundCheckConsent" 
                        fit="contain"
                        :preview-src-list="[currentDriver.documents.backgroundCheckConsent]"
                      />
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button 
            type="primary" 
            @click="auditQualification(currentDriver)"
            v-if="currentDriver && currentDriver.verified === 'pending'"
          >
            审核资质
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 资质审核对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      title="资质审核"
      width="600px"
    >
      <div class="audit-form" v-if="currentDriver">
        <el-form :model="auditForm" label-width="100px">
          <el-form-item label="司机信息">
            <div>姓名: {{ currentDriver.name }}</div>
            <div>ID: {{ currentDriver.id }}</div>
          </el-form-item>
          <el-form-item label="审核结果">
            <el-radio-group v-model="auditForm.result">
              <el-radio label="verified">通过</el-radio>
              <el-radio label="rejected">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审核备注">
            <el-input
              v-model="auditForm.remark"
              type="textarea"
              :rows="4"
              placeholder="请输入审核意见或说明"
            />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAudit">确认审核</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'

// 加载状态
const loading = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 筛选条件
const filters = reactive({
  status: '',
  verified: '',
  keyword: ''
})

// 重置筛选条件
const resetFilters = () => {
  filters.status = ''
  filters.verified = ''
  filters.keyword = ''
  searchDrivers()
}

// 搜索司机
const searchDrivers = () => {
  loading.value = true
  // 模拟API请求
  setTimeout(() => {
    // 这里实际项目中应该调用API
    loading.value = false
    ElMessage.success('搜索完成')
  }, 500)
}

// 刷新数据
const refreshData = () => {
  ElMessage.success('数据已刷新')
  fetchDriversList()
}

// 获取司机列表数据
const fetchDriversList = () => {
  loading.value = true
  // 模拟API请求
  setTimeout(() => {
    // 这里实际项目中应该调用API
    loading.value = false
  }, 500)
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchDriversList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchDriversList()
}

// 司机数据
const driversList = ref([
  {
    id: 'D2023001',
    name: '张师傅',
    phone: '13900001111',
    email: 'zhang@example.com',
    gender: '男',
    age: 35,
    joinDate: '2023-01-15',
    licenseType: 'C1',
    drivingYears: 10,
    carType: '大众帕萨特',
    carNumber: '京A12345',
    carColor: '黑色',
    passengerCapacity: 4,
    verified: 'verified',
    status: 'online',
    rating: 4.8,
    stats: {
      totalOrders: 256,
      completionRate: 98.5,
      totalIncome: 25680.50
    },
    documents: {
      idCardFront: 'https://via.placeholder.com/300x200?text=身份证正面',
      idCardBack: 'https://via.placeholder.com/300x200?text=身份证反面',
      drivingLicense: 'https://via.placeholder.com/300x200?text=驾驶证',
      vehicleLicense: 'https://via.placeholder.com/300x200?text=行驶证',
      vehiclePhoto: 'https://via.placeholder.com/300x200?text=车辆照片',
      backgroundCheckConsent: 'https://via.placeholder.com/300x200?text=背景调查授权书'
    }
  },
  {
    id: 'D2023002',
    name: '李师傅',
    phone: '13900002222',
    email: 'li@example.com',
    gender: '男',
    age: 28,
    joinDate: '2023-02-10',
    licenseType: 'C1',
    drivingYears: 5,
    carType: '丰田卡罗拉',
    carNumber: '京B67890',
    carColor: '白色',
    passengerCapacity: 4,
    verified: 'verified',
    status: 'busy',
    rating: 4.5,
    stats: {
      totalOrders: 120,
      completionRate: 97.0,
      totalIncome: 12350.75
    },
    documents: {
      idCardFront: 'https://via.placeholder.com/300x200?text=身份证正面',
      idCardBack: 'https://via.placeholder.com/300x200?text=身份证反面',
      drivingLicense: 'https://via.placeholder.com/300x200?text=驾驶证',
      vehicleLicense: 'https://via.placeholder.com/300x200?text=行驶证',
      vehiclePhoto: 'https://via.placeholder.com/300x200?text=车辆照片',
      backgroundCheckConsent: 'https://via.placeholder.com/300x200?text=背景调查授权书'
    }
  },
  {
    id: 'D2023003',
    name: '王师傅',
    phone: '13900003333',
    email: 'wang@example.com',
    gender: '男',
    age: 42,
    joinDate: '2023-03-05',
    licenseType: 'B2',
    drivingYears: 15,
    carType: '别克GL8',
    carNumber: '京C54321',
    carColor: '银灰色',
    passengerCapacity: 7,
    verified: 'pending',
    status: 'offline',
    rating: 0,
    stats: {
      totalOrders: 0,
      completionRate: 0,
      totalIncome: 0
    },
    documents: {
      idCardFront: 'https://via.placeholder.com/300x200?text=身份证正面',
      idCardBack: 'https://via.placeholder.com/300x200?text=身份证反面',
      drivingLicense: 'https://via.placeholder.com/300x200?text=驾驶证',
      vehicleLicense: 'https://via.placeholder.com/300x200?text=行驶证',
      vehiclePhoto: 'https://via.placeholder.com/300x200?text=车辆照片',
      backgroundCheckConsent: 'https://via.placeholder.com/300x200?text=背景调查授权书'
    }
  },
  {
    id: 'D2023004',
    name: '赵师傅',
    phone: '13900004444',
    email: 'zhao@example.com',
    gender: '女',
    age: 30,
    joinDate: '2023-02-20',
    licenseType: 'C1',
    drivingYears: 8,
    carType: '本田思域',
    carNumber: '京D13579',
    carColor: '红色',
    passengerCapacity: 4,
    verified: 'verified',
    status: 'suspended',
    rating: 4.2,
    stats: {
      totalOrders: 85,
      completionRate: 94.5,
      totalIncome: 8760.30
    },
    documents: {
      idCardFront: 'https://via.placeholder.com/300x200?text=身份证正面',
      idCardBack: 'https://via.placeholder.com/300x200?text=身份证反面',
      drivingLicense: 'https://via.placeholder.com/300x200?text=驾驶证',
      vehicleLicense: 'https://via.placeholder.com/300x200?text=行驶证',
      vehiclePhoto: 'https://via.placeholder.com/300x200?text=车辆照片',
      backgroundCheckConsent: 'https://via.placeholder.com/300x200?text=背景调查授权书'
    }
  }
])

// 计算总数
total.value = driversList.value.length

// 司机详情对话框
const detailDialogVisible = ref(false)
const currentDriver = ref(null)
const activeTab = ref('basic')
let orderChart = null
const orderChartRef = ref(null)

// 显示司机详情
const showDriverDetail = (driver) => {
  currentDriver.value = driver
  detailDialogVisible.value = true
  activeTab.value = 'basic'
  
  // 等待DOM更新后初始化图表
  nextTick(() => {
    if (activeTab.value === 'statistics') {
      initOrderChart()
    }
  })
}

// 初始化订单图表
const initOrderChart = () => {
  if (!orderChartRef.value) return
  
  if (orderChart) {
    orderChart.dispose()
  }
  
  orderChart = echarts.init(orderChartRef.value)
  
  const option = {
    title: {
      text: '近30天接单情况'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['接单数', '完成数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: Array.from({length: 30}, (_, i) => {
        const date = new Date()
        date.setDate(date.getDate() - 29 + i)
        return `${date.getMonth() + 1}/${date.getDate()}`
      })
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '接单数',
        type: 'line',
        data: [5, 7, 4, 9, 6, 8, 10, 8, 7, 5, 12, 11, 9, 8, 7, 10, 8, 6, 9, 11, 12, 10, 9, 8, 7, 5, 6, 8, 10, 11]
      },
      {
        name: '完成数',
        type: 'line',
        data: [5, 6, 4, 8, 6, 8, 9, 8, 7, 5, 11, 10, 9, 8, 7, 9, 8, 6, 8, 10, 11, 9, 9, 8, 7, 5, 6, 7, 9, 10]
      }
    ]
  }
  
  orderChart.setOption(option)
}

// 监听标签页变化
watch(activeTab, (newVal) => {
  if (newVal === 'statistics') {
    nextTick(() => {
      initOrderChart()
    })
  }
})

// 资质审核对话框
const auditDialogVisible = ref(false)
const auditForm = reactive({
  result: 'verified',
  remark: ''
})

// 审核资质
const auditQualification = (driver) => {
  currentDriver.value = driver
  auditForm.result = 'verified'
  auditForm.remark = ''
  auditDialogVisible.value = true
}

// 提交审核
const submitAudit = () => {
  // 模拟API请求
  // 在实际项目中，应该调用API提交审核结果
  
  // 更新司机资质状态
  if (currentDriver.value) {
    currentDriver.value.verified = auditForm.result
    
    // 更新列表中的司机信息
    const driverIndex = driversList.value.findIndex(d => d.id === currentDriver.value.id)
    if (driverIndex !== -1) {
      driversList.value[driverIndex].verified = auditForm.result
    }
    
    ElMessage.success('审核提交成功')
    auditDialogVisible.value = false
  }
}

// 切换司机状态（暂停/恢复服务）
const toggleDriverStatus = (driver) => {
  const action = driver.status !== 'suspended' ? '暂停' : '恢复'
  
  ElMessageBox.confirm(`确定要${action}该司机的服务吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟API请求
    // 在实际项目中，应该调用API更新司机状态
    
    if (driver.status !== 'suspended') {
      driver.status = 'suspended'
    } else {
      driver.status = 'offline'
    }
    
    ElMessage.success(`已${action}司机服务`)
  }).catch(() => {})
}

// 组件挂载后执行
onMounted(() => {
  fetchDriversList()
})
</script>

<style scoped>
.drivers-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.header-title .el-icon {
  margin-right: 8px;
  font-size: 20px;
}

.filter-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.drivers-list {
  margin-top: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.driver-detail {
  max-height: 60vh;
  overflow-y: auto;
}

.stat-card {
  height: 120px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.stat-header {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.chart-container {
  height: 300px;
  margin-top: 20px;
}

.documents-container {
  padding: 10px;
}

.document-card {
  margin-bottom: 20px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  overflow: hidden;
}

.document-title {
  background-color: #f5f7fa;
  padding: 10px;
  font-size: 14px;
  font-weight: bold;
  border-bottom: 1px solid #EBEEF5;
}

.document-image {
  height: 180px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f9f9f9;
}

.document-image .el-image {
  max-height: 160px;
  max-width: 100%;
}

.audit-form {
  padding: 20px;
}

@media (max-width: 768px) {
  .stat-card {
    height: 100px;
  }
  
  .document-image {
    height: 150px;
  }
}
</style> 